package com.teamwork.module03.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.teamwork.common.entity.common.UserIcon;
import com.teamwork.module03.service.AuthorService;
import com.teamwork.module03.service.RegisterService;
import com.teamwork.module03.service.UserIconService;
import com.teamwork.module03.service.UserService;
import com.teamwork.module03.util.EmailUtil;
import com.teamwork.common.entity.common.User;
import com.teamwork.common.result.Result;
import com.teamwork.common.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class RegisterServiceImpl implements RegisterService {
      @Resource
      private UserService userService;
      @Resource
      private RedisUtil redisUtil;
      @Resource
      private EmailUtil emailUtil;
      @Resource
      private BCryptPasswordEncoder passwordEncoder;
      @Resource
      private AuthorService authorService;
      @Resource
      private UserIconService userIconService;
    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public Result register(User user, BindingResult result) {

        String username = user.getUsername();
        String password = user.getPassword();
        String email = user.getEmail();
        if(username==null || password==null || email==null ){
            return  Result.failure("所有项都不能为空");
        }

        if (result.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            result.getFieldErrors().forEach(item -> {
                String msg = item.getDefaultMessage();
                String field = item.getField();
                map.put(field, msg);
            });
            //System.out.println(map);
            Object err = JSONObject.toJSON(map);
            return Result.failure("用户提交格式不正确",err);
        }

        //全都没问题之后在注册
        //先查询用户名是否已经被注册
        User one = userService.getByUsername(username);
        if(one!=null){
            return Result.failure("用户名已存在！");
        }

        User one2  =userService.getByEmail(email);
        if(one2!=null) return Result.failure("该邮箱已经被注册！");

        //用户名和邮箱都没有，则可以注册了
        //向该邮箱发送验证码

          emailUtil.sendCode(user, email);

         return Result.success("第一步成功！");
    }

    /**
     * 注册流程的第二步
     * @param username
     * @return
     */
    @Override
    public Result register2(String username,Integer code) {

        Object o = redisUtil.get("code:" + username);
        if(o==null){
            return Result.failure("验证码已失效，请重新发送");
        }
       // log.info("o:{}",o.toString());
        if(!o.toString().equals(code.toString())){
            return Result.failure("验证码错误，请重新输入！");
        }
        //都没问题，可以真的注册
        Object usero = redisUtil.get("register:" + username);
       // User user = JSON.parseObject((String) usero, User.class);
        User user = JSON.parseObject(JSON.toJSONString(usero), User.class);

        //先吧用户的密码编码一下
        String encodepass = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodepass);
        //给用户先设置为普通用户
        user.setRole(1);
        //设置状态为启用
        user.setStatus(1);
        //设置一个昵称
        String nickname = "用户_"+username;
        user.setNickname(nickname);

        boolean b = userService.save(user);
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,username);
        Long userid = userService.getOne(wrapper).getId();
        //往作者表中插入一条初始数据
        boolean ab = authorService.initOne(userid, username, nickname);
       //给用户设置一个默认图片
        userIconService.insertDefault(user);
        if(!b){
            log.error("用户注册写入用户表失败:"+username);
            return Result.failure(500,"注册失败，后台错误:写入用户表出错!");
        }else if(!ab){
            log.error("用户注册写入作者表失败:用户名:{}",username);
            return  Result.failure(500,"注册失败，后台错误：写入作者表出错！");
        }


        //删除验证码
        boolean del = redisUtil.del("code:" + username);
        if(!del){
            log.error("redis无法删除验证吗！！！");
        }
        log.info("用户注册:{}",user);
          return Result.success("注册成功！");

    }
}
